<template>
  <div class="register-page">
    <div class="logo">
      <img src="../../assets/images/登录页logo@2x.png" alt="">
    </div>
    <el-card class="el-card" shadow="always">
      <p>后台管理系统</p>
      <span @click="toLogin">去登录</span>
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="密码" prop="repassword">
          <el-input v-model="form.repassword" placeholder="请再次输入密码" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="register">注册</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { register } from '@/api/user'
export default {
  name: 'register-page',
  data () {
    const validateRepwd = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      form: {
        username: '',
        password: '',
        repassword: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: ['blur', 'change'] },
          { pattern: /^\w{1,10}$/, message: '请输入1~10个字母或数字', trigger: ['blur', 'change'] }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: ['blur', 'change'] },
          { min: 6, max: 15, message: '请输入6~15个字符', trigger: ['blur', 'change'] }
        ],
        repassword: [
          { validator: validateRepwd, trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  methods: {
    toLogin () {
      this.$router.push('/login')
    },
    async register () {
      try {
        await this.$refs.form.validate()
        const res = await register(this.form)
        this.$message.success('注册成功')
        this.$router.push('/login')
        this.$store.commit('user/setUserToken', res.token)
      } catch (e) {
        console.log(e)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.logo {
  img {
    width: 110px;
    height: 48px;
  }
}
.el-card {
  width: 540px;
  margin: 150px auto;
  text-align: center;
  p {
    font-size: 32px;
    color: #131523;
    letter-spacing: 0;
    font-weight: 400;
    margin-bottom: 8px;
  }
  span {
    font-size: 16px;
    color: #1E5EFF;
    &:hover {
      color: #4F81FF;
      cursor: pointer;
    }
  }
  .el-button {
    width: 500px;
    margin-top: 24px;
  }
}
</style>
